/*
 * Copyright (C) 2018 Logos Technology Ltd.
 */

package com.logos.common.widget;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.DrawableRes;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.annotation.StringRes;

import com.logos.common.R;
import com.logos.tool.AppConstants;
import com.logos.tool.file.StorageUtils;
import com.logos.tool.glide.OnLoadImageFileListener;
import com.logos.tool.image.ImageLoadUtils;
import com.logos.tool.file.FileUtils;
import com.logos.tool.log.LogUtil;

import java.io.File;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.ObservableSource;
import io.reactivex.ObservableTransformer;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by llx on 2018/8/29.
 */
public class CustomTakePhotoView extends LinearLayout {

    private Context mContext;
    private String mImagePath;
    private ImageView mImage;
    private ImageView mTipImage;
    private TextView mTipText;
    private LinearLayout mTipLinearLayout;

    public CustomTakePhotoView(@NonNull Context context) {
        this(context, null);
    }

    public CustomTakePhotoView(@NonNull Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public CustomTakePhotoView(@NonNull Context context,
                               @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        mContext = context;
        initView();
    }

    private void initView() {
        View rootView = LayoutInflater.from(mContext).inflate(R.layout.take_photo_view, this);
        mImage = rootView.findViewById(R.id.iv_image);
        mTipImage = rootView.findViewById(R.id.iv_tip);
        mTipText = rootView.findViewById(R.id.tv_tip);
        mTipLinearLayout = rootView.findViewById(R.id.ll_tip);
    }

    /**
     * 设置Image图片地址
     *
     * @param imagePath 图片地址 本地或者网络
     */
    public void setImagePath(String imagePath) {
        if (imagePath.startsWith("http")) {
            ImageLoadUtils.loadImageView(mContext, imagePath, new OnLoadImageFileListener() {
                @Override
                public void onLoadStarted() {

                }

                @Override
                public void onLoadSuccess(final File file) {
                    Observable observable = Observable.create(new ObservableOnSubscribe<String>() {
                        @Override
                        public void subscribe(final ObservableEmitter<String> observableOnSubscribe)
                                throws Exception {
                            String destPath = StorageUtils.getStorage().getAbsolutePath()
                                    + AppConstants.FILE_ROOT_NAME
                                    + "/camera/";//照片保存路径
                            String fileName = System.currentTimeMillis() + ".jpg";
                            boolean copyFile = FileUtils.copyFile(file, destPath, fileName);
                            if (copyFile) {
                                observableOnSubscribe.onNext(destPath + fileName);
                            }

                        }
                    });
                    observable.compose(observableTransformer()).subscribe(new Observer<String>() {
                        @Override
                        public void onSubscribe(Disposable disposable) {
                        }

                        @Override
                        public void onNext(String name) {
                            mImagePath = name;
                            showImage(mImagePath);
                            LogUtil.debug("CustomTakePhotoView", "NetUrl: " + mImagePath);
                        }

                        @Override
                        public void onError(Throwable throwable) {
                        }

                        @Override
                        public void onComplete() {
                        }
                    });

                }

                @Override
                public void onLoadFailed() {

                }
            });
        } else {
            mImagePath = imagePath;
            LogUtil.debug("CustomTakePhotoView", "LocalUrl: " + mImagePath);
            showImage(imagePath);
        }

    }

    private <T> ObservableTransformer<T, T> observableTransformer() {

        return new ObservableTransformer<T, T>() {

            @Override
            public ObservableSource<T> apply(Observable<T> upstream) {
                return upstream.subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread());
            }
        };
    }

    private void showImage(Object object) {
        mTipLinearLayout.setVisibility(GONE);
        mImage.setVisibility(VISIBLE);
        ImageLoadUtils.loadImageView(mContext, object, mImage);
    }

    public String getImagePath() {
        return mImagePath;
    }

    /**
     * 设置文字
     *
     * @param tipText 文本信息
     */
    public void setTipText(String tipText) {
        mTipText.setText(tipText);
    }

    /**
     * 设置文字
     *
     * @param resid 文字资源
     */
    public void setTipText(@StringRes int resid) {
        mTipText.setText(resid);
    }

    /**
     * 设置图片资源
     *
     * @param resid 图片资源文件
     */
    public void setTipImage(@DrawableRes int resid) {
        mTipImage.setBackgroundResource(resid);
    }

    /**
     * 设置图片
     *
     * @param drawable drawable
     */
    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
    public void setTipImage(Drawable drawable) {
        mTipImage.setBackground(drawable);
    }
}
